import time
import requests
from urllib.parse import urlencode
from random import random

DEFAULT_USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36'
SERVER_URL_HOST = 'www.agefans.vip'


def getJsDateTime():
    """
    等价于Js中的 new Date().getTime()
    :return: 13位时间戳
    """
    return int(time.time() * 1000)


def get_play_pck(t1: int):
    t1 = round(t1 / 0x3e8) >> 0x5
    return (t1 * (t1 % 0x1000) * 0x3 + 0x1450f) * (t1 % 0x1000) + t1


def get_play_pck2(k1: str):
    k_sub = k1[-0x1]
    while True:
        t2 = str(getJsDateTime())
        t3 = t2[-3:-1] + t2[-1]
        if t3.find(k_sub) >= 0x0:
            return t2


def found_cookie(cookie_str: str, key: str):
    index = 0
    for sub in [key, '=']:
        if index > -1:
            index = cookie_str.find(sub, index)
        else:
            return ''
    index += 1
    return cookie_str[index:cookie_str.find(';', index)]


def getEncryptionParameter(aid, play_index, ep_index):
    with requests.get(url=f'https://{SERVER_URL_HOST}/play/{aid}?playid={play_index}_{ep_index}',
                      headers={'user-agent': DEFAULT_USER_AGENT}, stream=True) as req:
        setCookie = req.headers['Set-Cookie']
        t1 = found_cookie(setCookie, 't1')
        k1 = found_cookie(setCookie, 'k1')
        return {
            'k1': k1,
            't1': t1,
            'k2': get_play_pck(int(t1)),
            't2': get_play_pck2(k1),
            "fat_t": getJsDateTime(),
            "fac_c": 1
        }


def age_cb_get_play_url(aid, play_index, ep_index):
    """
    :param aid 动画ID
    :param play_index 播放页面号
    :param ep_index 集号
    """
    cookie = getEncryptionParameter(aid, play_index, ep_index)
    cookie = urlencode(cookie).replace('&', ';') + ';'
    time.sleep(1)
    rep = requests.get(
        url=f'https://{SERVER_URL_HOST}/_getplay?aid={aid}&playindex={play_index}&epindex={ep_index}&r={random()}',
        headers={
            'referer': f'https://{SERVER_URL_HOST}/play/{aid}?playid={play_index}_{ep_index}',
            'user-agent': DEFAULT_USER_AGENT,
            'cookie': cookie
        })
    print(rep.status_code)
    return rep.text